package mz.matafe.bolao

/**
 * Authenticate Service
 *
 * <p>Handle the authetication
 * <p>Overiden from acegi plugin
 *
 * @since 0.0.1
 * @author <a href="mailto:matafe@gmail.com">Maurício T. Ferraz</a>
 */
class AuthenticateService extends org.grails.plugins.springsecurity.service.AuthenticateService{

    boolean transactional = false

    void clearCachedRequestmaps() {
        if(objectDefinitionSource != null){
            objectDefinitionSource.reset()
        }
    }

    void deleteRole(role) {
        def conf = getSecurityConfig().security
        String configAttributeName = conf.requestMapConfigAttributeField
        role.getClass().withTransaction { status ->
            if (conf.useRequestMapDomainClass) {
                String roleName = role."$conf.authorityField"
                def requestmaps = findRequestmapsByRole(roleName, role.getClass(), conf)
                requestmaps.each { rm ->
                    String configAttribute = rm."$configAttributeName"
                    if (configAttribute.equals(roleName)) {
                        rm.delete()
                    }
                    else {
                        List parts = configAttribute.split(',') as List
                        parts.remove roleName
                        rm."$configAttributeName" = parts.join(',')
                    }
                }
                clearCachedRequestmaps()
            }
            role.delete()
        }
    }

    boolean updateRole(role, newProperties) {
        def conf = getSecurityConfig().security
        String authorityField = conf.authorityField
        String oldRoleName = role."$authorityField"
        role.properties = newProperties
        String configAttributeName = conf.requestMapConfigAttributeField
        if (conf.useRequestMapDomainClass) {
            String newRoleName = role."$authorityField"
            if (newRoleName != oldRoleName) {
                def requestmaps = findRequestmapsByRole(oldRoleName, role.getClass(), conf)
                requestmaps.each { rm ->
                    rm."$configAttributeName" = rm."$configAttributeName".replace(oldRoleName, newRoleName)
                }
            }
            clearCachedRequestmaps()
        }
        role.save()
        return !role.hasErrors()
    }
}
